<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { useRealnameStore } from '@/stores/realnameStore.js'
import { ElMessage } from 'element-plus'

const realnameStore = useRealnameStore()
const emit = defineEmits(['update:visible', 'success'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  authData: {
    type: Object,
    default: () => ({})
  }
})

const formRef = ref()
const loading = ref(false)

const form = reactive({
  userId: '',
  authStatus: 2, // 2-通过 3-拒绝
  rejectReason: ''
})

const rules = {
  authStatus: [
    { required: true, message: '请选择审核状态', trigger: 'change' }
  ],
  rejectReason: [
    {
      validator: (rule, value, callback) => {
        if (form.authStatus === 3 && !value) {
          callback(new Error('拒绝原因不能为空'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 监听认证数据变化
watch(
    () => props.authData,
    (newAuthData) => {
      if (newAuthData) {
        form.userId = newAuthData.userId
      }
    },
    { immediate: true }
)

const handleClose = () => {
  form.authStatus = 2
  form.rejectReason = ''
  emit('update:visible', false)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()

  try {
    loading.value = true
    await realnameStore.verifyAuth({ ...form })
    ElMessage.success('审核操作成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('审核操作失败:', error)
    ElMessage.error('审核失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-dialog
      :model-value="visible"
      title="实名认证审核"
      width="500px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-loading="loading"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="form.userId" disabled />
      </el-form-item>

      <el-form-item label="审核状态" prop="authStatus">
        <el-radio-group v-model="form.authStatus">
          <el-radio :label="2">通过</el-radio>
          <el-radio :label="3">拒绝</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
          v-if="form.authStatus === 3"
          label="拒绝原因"
          prop="rejectReason"
      >
        <el-input
            v-model="form.rejectReason"
            type="textarea"
            :rows="3"
            placeholder="请输入拒绝原因"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>